<template>
  <div>
    <!-- 筛选 订单状态 -->
    <ContentWrap :show-border="false">
      <SearchBox
        :queryForm="searchList"
        :showExpland="false"
        :show-export="false"
        :showLen="5"
        @changeVal="handleChange"
        @query="handleSearchQuery"
      />
    </ContentWrap>
    <div class="w-full h-[1px]" style="border-bottom: 1px dashed #ddd"></div>
    <ContentWrap :show-border="false">
      <div class="flex items-center mt-[20px] btnbox">
        <div class="flex items-center mr-[20px]">
          <div
            class="bg w-[14px] h-[14px] mr-[5px]"
            style="
              background-image: url(https://img.alicdn.com/imgextra/i1/801089336/O1CN01eYDHP42Ipwk9q9ztR_!!801089336.png);
            "
          ></div>
          已选 <span class="text-[#3721FF]">{{ selectionRow.length }}</span> 项</div
        >
        <el-button type="primary" color="#3721FF" @click="handleAdd">新增</el-button>
        <el-button @click="handleUpdateAdvertise">更新账户数据</el-button>
        <el-button @click="handleBatchCheck" :loading="loading">批量验证</el-button>
      </div>
    </ContentWrap>
    <ContentWrap :show-border="false">
      <el-table :data="tableData" class-name="myTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="广告账户名称" prop="advertiserName" width="160" />
        <el-table-column label="广告账户ID" prop="advertiserId" width="160" />
        <el-table-column label="app_id" prop="appId" width="160" />
        <el-table-column label="状态" prop="status" width="100">
          <template #default="{ row }">
            <div class="flex items-center items" v-if="row.status == 0">
              <img :src="SuccessPng" class="w-[12px] h-[12px] object-contain" />
              <div class="text-[14px] text-[#101010] ml-[4px] txt">正常</div>
            </div>
            <div class="flex items-center items" v-else>
              <img :src="FailPng" class="w-[12px] h-[12px] object-contain" />
              <div class="text-[14px] text-[#101010] ml-[4px] txt">停用</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="更新状态" prop="statusText" width="110">
          <template #default="{ row }">
            {{ row.updateStatus === 0 ? '未完成' : '已完成' }}
          </template>
        </el-table-column>
        <el-table-column label="是否启用" prop="status" width="150">
          <template #default="{ row }">
            <el-switch
              class="ml-2"
              v-model="row.status"
              inline-prompt
              active-text="停用"
              inactive-text="启用"
              :active-value="0"
              :inactive-value="1"
              style="--el-switch-on-color: #3721ff; --el-switch-off-color: #bfbfbf"
              :before-change="() => handleSwitchChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="deptName" width="150" />
        <el-table-column label="人员" prop="createName" />
        <el-table-column label="创新时间/更新时间" prop="createTime" width="170">
          <template #default="{ row }">
            {{ formatTime(row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <div class="flex">
              <el-button
                type="primary"
                style="width: 35px !important; padding: 0 !important"
                link
                @click="Edit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="primary"
                style="width: 35px !important; padding: 0 !important"
                link
                @click="Check(row)"
              >
                验证
              </el-button>
              <el-button
                type="danger"
                style="width: 35px !important; padding: 0 !important"
                link
                @click="Del(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </ContentWrap>
    <InfoAction
      ref="infoActionRef"
      :curAdvertiser="curAdertiser"
      :mode="curMode"
      :depatList="depatList"
      :appList="appList"
      @refresh="getList"
    />
  </div>
</template>
<script setup lang="ts">
import OrderStatusMenu from '@/views/trade/components/OrderStatusMenu.vue'
import type { TradeOrderQueryVO } from '@/api/mall/trade/order'
import SuccessPng from '@/assets/ad/success.png'
import FailPng from '@/assets/ad/fail.png'
import InfoAction from './components/InfoAction.vue'
import { getSimpleDeptList } from '@/api/system/dept'
import { getUserPage } from '@/api/system/user'
import { getUserPageNew } from '@/api/member/user'
import { throttle, buildTree, formatTime } from '@/utils'
import { AdvertiserApi, AdvertiserVO } from '@/api/ad/advertiser'
import { AppSocialApi } from '@/api/ad/appSocial'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { AdsetEverdayCostApi } from '@/api/ad/adseteverdaycost'
import dayjs from 'dayjs'

const { loadStart, loadDone } = usePageLoading()

const message = useMessage()

const isDragging = ref(false)
const startX = ref(0)
const translateX = ref(0)
const scrollLeft = ref(0)
const infoActionRef = ref<InstanceType<typeof InfoAction> | null>(null)
const minTranslateX = ref(0)

const curAdertiser = ref<AdvertiserVO>()

const curMode = ref('add')

const depatList = ref([])

const appList = ref([])

const selectionRow = ref([])

const createNameList = ref([])

const total = ref(0)

const loading = ref(false)

const initQueryParams = {
  pageNo: 1,
  pageSize: 10,
  advertiserName: undefined,
  status: undefined,
  deptId: undefined,
  deptName: undefined,
  createName: undefined,
  createTime: []
}

const queryParams = ref({
  ...initQueryParams
})

const startDrag = (event: MouseEvent) => {
  if (minTranslateX.value > 0) return
  isDragging.value = true
  startX.value = event.pageX
}

const stopDrag = () => {
  isDragging.value = false
}

const doDrag = (event: MouseEvent) => {
  if (!isDragging.value || minTranslateX.value > 0) return
  event.preventDefault()
  const x = event.pageX
  let walk = x - startX.value // 计算移动的距离
  translateX.value += walk // 更新位移
  if (translateX.value > 0) translateX.value = 0
  if (translateX.value < minTranslateX.value) translateX.value = minTranslateX.value
  startX.value = x // 更新起始位置
}

const tableData = ref([])

const searchList = ref<TradeOrderQueryVO[]>([
  {
    label: '部门',
    code: 'deptId',
    type: 'treeSelect',
    options: depatList.value
  },
  {
    label: '人员',
    code: 'createName',
    type: 'select',
    options: createNameList.value
  },
  {
    label: '广告账户ID',
    code: 'advertiserId',
    type: 'input'
  },
  {
    label: '广告账户名称',
    code: 'advertiserName',
    type: 'input'
  },
  {
    label: '账户状态',
    code: 'status',
    type: 'select',
    options: [
      {
        label: '正常',
        value: 0
      },
      {
        label: '停用',
        value: 1
      }
    ]
  }
])
const orderStatusList = [
  {
    label: '按成员',
    value: 0
  },
  {
    label: '按部门',
    value: 1
  },
  {
    label: '按地区',
    value: 2
  },
  {
    label: '按商品',
    value: 3
  }
]
const handleOrderStatus = (status: number) => {
  //获取指定订单状态
  console.log(status, 'status')
}

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
  queryParams.value = {
    ...initQueryParams,
    ...val
  }
  getList()
}

const handleChange = (val) => {
  if (val.form.deptId) {
    queryParams.value.deptId = val.form.deptId
  }
}
watch(
  () => queryParams.value.deptId,
  () => {
    getCreateNameList()
  }
)
//查询部门人员
const getCreateNameList = async () => {
  const res = await getUserPageNew({ pageNo: 1, pageSize: 99, deptId: queryParams.value.deptId })
  createNameList.value = res.map((item) => {
    return {
      label: item.nickname,
      value: item.nickname
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'createName') {
      item.options = createNameList.value
    }
  })
}

/**更改启停用状态*/
const handleSwitchChange = async (row) => {
  const text = row.status === 1 ? '启用' : '停用'

  try {
    await message.confirm(`确认要${text}吗？`)
    await AdvertiserApi.updateStatus({
      id: row.id
    })
    message.success(`${text}成功`)
    getList()
    return true
  } catch {
    return false // 用户取消，返回不允许切换
  }
}

const handleAdd = () => {
  curMode.value = 'add'
  curAdertiser.value = { status: 0 } as AdvertiserVO
  infoActionRef.value?.show()
}

/**表格多选*/
const handleSelectionChange = (selection) => {
  selectionRow.value = selection
  console.log(selection, 'selection')
}

/**编辑*/
const Edit = (row) => {
  curMode.value = 'edit'
  curAdertiser.value = row
  infoActionRef.value?.show()
}
/**删除*/
const Del = async (row) => {
  try {
    await message.confirm(`确认要删除吗？`)
    loading.value = true
    await AdvertiserApi.deleteAdvertiser(row.id)
    message.success('删除成功')
    getList()
  } catch (err) {
    message.error(err.msg)
  } finally {
    loading.value = false
  }
}

/**验证*/
const Check = (row) => {
  checkAdvertiserRequest(row.id)
}

/**批量验证*/
const handleBatchCheck = () => {
  if (selectionRow.value.length === 0) {
    message.warning('请选择要验证的账户')
    return
  }
  const ids = selectionRow.value
    .map((item) => {
      return item.id
    })
    .join(',')
  checkAdvertiserRequest(ids)
}
/**验证操作*/
const checkAdvertiserRequest = async (ids: string) => {
  loadStart()
  try {
    loading.value = true
    const res = await AdvertiserApi.checkAdvertiser(ids)
    message.success(res)
  } catch (err) {
    message.error(err.msg)
  } finally {
    loading.value = false
    loadDone()
  }
}
/**批量更新账户数据*/
const handleUpdateAdvertise = async (row) => {
  const formattedDate = dayjs().format('YYYY-MM-DD')
  if (selectionRow.value.length === 0) {
    message.warning('请选择要更新的账户')
    return
  }
  const ids = selectionRow.value.map((item) => {
    return item.advertiserId
  })
  loadStart()
  try {
    loading.value = true
    const res = await AdsetEverdayCostApi.syncCost({ advertiserIds: ids, date: formattedDate })
    message.success(res)
  } catch (err) {
    message.error(err.msg)
  } finally {
    loading.value = false
    loadDone()
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AdvertiserApi.getAdvertiserPage(queryParams.value)
    tableData.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const init = async () => {
  const [depatRes, appListRes] = await Promise.all([
    getSimpleDeptList(),
    AppSocialApi.getAppSocialPage({ pageNum: 1, pageSize: 99 })
  ])
  depatList.value = buildTree(depatRes)
  searchList.value.map((item) => {
    if (item.code === 'deptId') {
      item.options = depatList.value
    }
  })
  appList.value = appListRes.list.map((item) => {
    return {
      label: item.appName,
      value: item.appId
    }
  })
}

onMounted(() => {
  init()
  nextTick(() => {
    getList()
  })
})
</script>
<style lang="scss" scoped>
.scrollbox {
  overflow-x: auto; /* 允许横向滚动 */
}
:deep(.el-table.myTable thead tr) {
  background-color: #f7f7fb;
  border-radius: 4px;
  overflow: hidden;
}
:deep(.el-table.myTable thead th.el-table__cell) {
  background-color: #f7f7fb;
}
:deep(.el-button) {
  height: 45px !important;
  border-radius: 23px !important;
  padding: 0 22px !important;
}
</style>
